package com.hmall.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //要不要拦截
        String url = request.getPath().toString();
        List<String> excludePaths = authProperties.getExcludePaths();
        if (!CollectionUtil.isEmpty(excludePaths)) {
            for (String excludePath : excludePaths) {
                if (antPathMatcher.match(excludePath, url)){
                    return chain.filter(exchange);
                }
            }
        }
        String authorization = request.getHeaders().getFirst("authorization");
        if (!StringUtils.hasLength(authorization)){
           response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            Long userId = jwtTool.parseToken(authorization);
            log.info("解析到userId:{}", userId);
            // TODO 如果解析成功，把解析出来的用户信息继续向微服务传递
            request.mutate().header("user-info",""+userId);
            return chain.filter(exchange);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
